package com.cn.txx.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;


public class myexp {

    /**
     * @param args
     */
    private static int threadCount = 3;
    private static int blockSize;
    private static String path = "D:\\a.txt";
    private static int currentRunThreadCount = 0;
    public static void main(String[] args) {
        
        try {
        	File file = new File(path);
        	int fileLength = (int) file.length();
            @SuppressWarnings("resource")
			RandomAccessFile randomAccessFile = new RandomAccessFile(new File(getFileName(path)), "rw");
            randomAccessFile.setLength(fileLength);
            blockSize = fileLength / threadCount;
            for(int i = 0; i < threadCount; i ++) {
                int startThread = i * blockSize;
                int endThread = (i + 1) * blockSize - 1;
                if( i == blockSize - 1) endThread = fileLength -1;
                new DownloadThread(i, startThread, endThread).start();
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    
    public static class DownloadThread extends Thread {
        private int threadId;
        private int endThread;
        private int startThred;
        public DownloadThread(int threadId, int startThred, int endThread) {
            this.threadId = threadId;
            this.startThred = startThred;
            this.endThread = endThread;
        }
        public void run() {    
            synchronized (DownloadThread.class) {
                currentRunThreadCount += 1;
            }
            //分段请求网络连接，分段保存在本地
            try {
                System.err.println("理论线程:"+threadId+",开始位置:"+startThred+",结束位置:"+endThread);
                File file = new File(threadId+".txt");
                if(file.exists()) {    //是否断点
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                    String lastPostion_str = bufferedReader.readLine();
                    startThred = Integer.parseInt(lastPostion_str);
                    bufferedReader.close();
                }
                //设置分段下载的头信息  Range:做分段
                    FileInputStream fis = new FileInputStream(new File(path));
                    System.out.println(getFileName(path));
                    String fileName = getFileName(path);
                    System.out.println(fileName);
                    RandomAccessFile randomAccessFile = new RandomAccessFile(new File(fileName), "rw");
                    randomAccessFile.seek(startThred);
                    byte[] buffer = new byte[1024*10];
                    int length = -1;
                    int total = 0;//记录下载的总量
                    System.err.println("实际线程:"+threadId+",开始位置:"+startThred+",结束位置:"+endThread);
                    while((length = fis.read(buffer)) != -1) {
                        randomAccessFile.write(buffer, 0, length);
                        total += length;
                        int currentThreadPostion = startThred + total;
                        RandomAccessFile randomAccessFile2 = new RandomAccessFile(file, "rwd");
                        randomAccessFile2.write(String.valueOf(currentThreadPostion).getBytes());
                        randomAccessFile2.close();
                    }
                    randomAccessFile.close();
                    fis.close();
                    System.err.println("线程:"+threadId+"下载完毕");
                    synchronized (DownloadThread.class) {
                        currentRunThreadCount -= 1;
                        if(currentRunThreadCount == 0){
                            for(int i = 0; i < threadCount; i ++) {
                                File file2 = new File(i+".txt");
                                file2.delete();
                            }
                        }
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.run();
        }
    }
    
    public static String getFileName(String path) {
        return path.substring(path.lastIndexOf("/")+1);
    }

}